package org.effdom.example;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.effdom.Document;
import org.effdom.DocumentFactory;
import org.effdom.io.DocumentReader;
import org.effdom.io.DocumentWriter;

public class HttpDomClient {


    public HttpDomClient() {
        super();
    }

    public void sendDocument() throws MalformedURLException, IOException {
            
            HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:8080").openConnection();
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
            
            // Create a EffDom document with root element containing the
            // attribute "Hello server"
            // Send the document over HTTP
            DocumentFactory factory = DocumentFactory.createInstance();
            Document doc = factory.createDocument();
            doc.rootElement((short)1).attr((short)2, "Hello server");
            DocumentWriter writer = factory.createDocumentWriter();
            writer.write(doc, out);

            out.close();
            
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                
                // Create a document reader and read the document from
                // the input stream.
                // Print the result.
                DocumentReader reader = factory.createDocumentReader();
                Document doc2 = reader.read(conn.getInputStream());
                
                System.out.println("Client, received document: " + doc2);
            } else {
                System.out.println("Get unexpected response code: " + conn.getResponseCode());
            }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            new HttpDomClient().sendDocument();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
